package com.dx.VegetableOxygenBarBackEnd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dx.VegetableOxygenBarBackEnd.common.BaseResponse;
import com.dx.VegetableOxygenBarBackEnd.common.ErrorCode;
import com.dx.VegetableOxygenBarBackEnd.common.ResultUtils;
import com.dx.VegetableOxygenBarBackEnd.exception.BusinessException;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.Team;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.User;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.UserTeam;
import com.dx.VegetableOxygenBarBackEnd.model.domain.vo.TeamUserVo;
import com.dx.VegetableOxygenBarBackEnd.service.CosService;
import com.dx.VegetableOxygenBarBackEnd.service.TeamService;
import com.dx.VegetableOxygenBarBackEnd.service.UserService;
import com.dx.VegetableOxygenBarBackEnd.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/cos")
@CrossOrigin(origins = "https://danma.icu", allowCredentials = "true")
public class CosController {
    @Resource
    private CosService cosService;
    @Resource
    private UserService userService;
    @Resource
    private TeamService teamService;


    /**上传头像
     *
     * @param file
     * @return
     */
    @PostMapping ("/upload")
    @Transactional
    public BaseResponse<Boolean> upload(@RequestParam("file") MultipartFile file, @RequestParam("avatarsUrl") String avatarsUrl,Long teamId,HttpServletRequest httpServletRequest){
        if(avatarsUrl.equals("user")){
            avatarsUrl = "avatarUsers/";
        }
        else if(avatarsUrl.equals("team")){
            avatarsUrl = "avatarTeams/";
        }
        try {
            // 校验文件是否为空
            if (file.isEmpty()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
            }
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (loginUser == null) {
                throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
            }
            // 删除旧头像
            // 获取用户当前头像 URL，准备删除
            String oldAvatarUrl = null;
            Long loginUserId = loginUser.getId();
            User user = userService.getById(loginUserId);
            Team team = teamService.getById(teamId);
            //如果队伍id为空，那么就是修改用户头像
            if(teamId == null){
                oldAvatarUrl = user.getAvatarUrl();
            }
            else{
                oldAvatarUrl = team.getTeamAvatar();
            }
            if (oldAvatarUrl != null && !oldAvatarUrl.isEmpty() && oldAvatarUrl.contains("shucai")) {
                boolean deleted = cosService.deleteFile(oldAvatarUrl,avatarsUrl);  // 删除旧头像文件
                if (deleted) {
                    log.info("旧头像删除成功: {}", oldAvatarUrl);
                } else {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧头像删除失败");
                }
            }
            // 调用 COS 服务上传文件
            String fileUrl = cosService.uploadFile(file,avatarsUrl);
            if(StringUtils.isBlank(fileUrl)){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "头像上传失败");
            }
            // 返回上传成功的响应
            log.info("文件上传成功, 文件访问URL: {}", fileUrl);
            boolean update = true;
            //todo  检验
            //将头像存储到用户的头像中执行更新操作
            if(teamId == null){
                loginUser.setAvatarUrl(fileUrl);
                QueryWrapper<User> updataQueryWrapper = new QueryWrapper<>();
                updataQueryWrapper.eq("id", loginUserId);
                update = userService.update(loginUser, updataQueryWrapper);
            }else{
                team.setTeamAvatar(fileUrl);
                QueryWrapper<Team> qw = new QueryWrapper<>();
                qw.eq("id", teamId);
                update= teamService.update(team, qw);
            }

            if(!update){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新头像失败");
            }
            return ResultUtils.success(true);
        } catch (BusinessException e) {
            log.error("文件上传业务错误: {}", e.getMessage());
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件上传失败");
        } catch (Exception e) {
            log.error("文件上传出现异常: {}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        }
    }


}
